//
//  JUFNAuthorViewModel.swift
//  WiBoPM
//
//  Created by 陈俊峰 on 2017/1/8.
//  Copyright © 2017年 陈俊峰. All rights reserved.
//

import UIKit

//实现swift与oc的无缝切换
private let documentPath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")
class JUFNAuthorViewModel: NSObject {
    
    //提供一个创建单例的对象
    static let shared = JUFNAuthorViewModel()
    //持有一个模型
    var userAcc : JUFNUserAccount?
    //持有一个头像的URL
    var avatarUrl:URL? {
            return URL(string: userAcc?.avatar_large ?? "")
        
    }
    
    
    //判断是否登录
    var uesrLogin:Bool{
        if userAcc != nil && isExpired == false {
            return true
        }
        return false
    }
    //这里做出判断,生命周期是否过期,nil可以发送消息
    var isExpired:Bool {
        if userAcc?.expires_date?.compare(Date()) == .orderedAscending {
            return true
        }
        return false
    }
    
    
    override init(){
        super.init()
       self.userAcc = self.loadUserAccount()
        
    }
    
    
    ///获取code后,获取access_token,给方法一个闭包,回调回去
    func loadRequest(code:String,complete:@escaping((Bool) -> ())){
        let accessTokenStr = "https://api.weibo.com/oauth2/access_token"
        let prameters:[String:Any] = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        JUFNetworkingTools.shared.request(method: .POST, urlString:accessTokenStr , prameters: prameters, finisnedClosure: { (resp:Any?, error:Error?) in
            if error == nil {
                let accessTokendict = resp as! [String:Any?]
                self.requestUserInfo(accessTokendict: accessTokendict,complete:complete)
            }
        })
    }
    
    
    ///请求用户信息
    private func requestUserInfo(accessTokendict:[String:Any?],complete:@escaping((Bool) -> ())) {
        //创建一个模型,将字典转化为模型
        let userInfoPrameters = [
            "access_token":accessTokendict["access_token"],
            "uid":accessTokendict["uid"]
        ]
        let uesrInfoUrlString = "https://api.weibo.com/2/users/show.json"
        JUFNetworkingTools.shared.request(method: .GET, urlString: uesrInfoUrlString, prameters: userInfoPrameters, finisnedClosure: {(resp:Any?,error:Error?) -> () in
            //将accessToken数据字典和请求到的userInfo合并到一个模型中去
            if error == nil {
                var userInfoDict = resp as! [String:Any?]
                for (key,value) in accessTokendict{
                    userInfoDict[key] = value
                }
                let account = JUFNUserAccount(dict: userInfoDict)
                NSKeyedArchiver.archiveRootObject(account, toFile: documentPath)
                self.userAcc = account
               complete(true)
                print(userInfoDict)
            }
        })
    }
    
    ///解档数据
    func loadUserAccount() -> JUFNUserAccount? {
      
        //条件语句必须是可选类型
        if let userAcc = NSKeyedUnarchiver.unarchiveObject(withFile: documentPath) as? JUFNUserAccount{
            return userAcc
        }
        //没有解包
        return nil
    }
    
    
    
    
}
